package com.ygxsk.carhome.ui.archive;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.tencent.mmkv.MMKV;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.event.EventAgreeMentDetail;
import com.ygxsk.carhome.listener.AuthorityCallbackListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.response.ArchivesManageVo;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.sys.PermissionInterceptor;
import com.ygxsk.carhome.sys.PermissionNameConvert;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.utils.CommTools;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-07-27  21:53
 * @Description:单个的合同详情,
 */
public class AgreenMentDetailActivity extends ErrorActivity implements ErrorParentExtraSingle, EasyPermissions.PermissionCallbacks {

    //合同 详情 右侧的【编辑】按钮
    @BindView(R.id.roundtextvieweditagreementright)
    RoundTextView roundTextViewEditAgreeMentRight;

    //该页面的一个刷新
    @BindView(R.id.refreshlayoutinagreementdetail)
    SmartRefreshLayout refreshLayoutInAgreeMentDetail;

    //合同类型
    @BindView(R.id.textview_agreen_type)
    TextView textView_agreen_type;

    //合同编号
    @BindView(R.id.textview_agreen_number)
    TextView textView_agreen_number;

    //合同签约时间
    @BindView(R.id.textview_agreen_time)
    TextView textView_agreen_time;

    //购车人
    @BindView(R.id.textview_agreen_person)
    TextView textView_agreen_person;

    //品牌型号
//    @BindView(R.id.textview_agreen_model)
//    TextView textView_agreen_model;

    //合同金额
    @BindView(R.id.textview_agreen_price)
    TextView textView_agreen_price;

    //合同金额
    @BindView(R.id.npl_item_moment_photos_agreen_detail)
    BGANinePhotoLayout npl_item_moment_photos_agreen_detail;

    //该页面仅仅只有预览的能力
    private static final int PRC_PHOTO_PREVIEW = 1;

    //这一条合同的携带数据，详情展示这条数据内的内容
    //携带详情的信息过去主要的是为了修改 客户信息和车辆信息
//    private InformationManageVoExtra extra_informationManageVoExtra;

    //这条从详情遍历出来的数据，不是携带的，因为有继承关系，不能序列化，
    private ArchivesManageVo archivesManageVo_outSide;

    //携带这条合同的 单独的id，然后遍历这条合同详情--小范畴的合同id;不是档案的id;
    private String extra_archivesId_single;
//  private String extra_archivesId;

    //携带 档案的id 档案盒子，大范畴的
    private String extra_informationId_id;
//  private String extra_vehicleid_id;

    //当前的这个九宫格图片信息
    private BGANinePhotoLayout mCurrentClickNpl;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        initViews();

        gainDatas();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_agreen_ment_detail;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

//      toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setTitle(getString(R.string.title_agreement_detail));

        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);

        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索客户信息，优先关闭软键盘
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        //应该是 还没有【被分配】被评估完毕的，还是可以再次编辑的
        toolbarHelper.setLayoutRight(false, 0, "", null);

        // : 2023-07-18 11:34 判断该订单的状态，是否是还可以再次编辑 ??
//        toolbarHelper.setLayoutRight(false, 0, "编辑", new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//                //历史记录的页面布局
//                Bundle extra_bundle = new Bundle();
////                //这里空携带,,编辑信息 ？
//                ActivityUtils.startActivity(extra_bundle, CarEvaluateAddSubmitActivity.class);
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        //

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }


    @Override
    protected void initViews() {

        //添加单个的，九宫格图片的添加
//        if (extra_informationManageVoExtra != null) {

//            ArrayList<ArchivesManageSingleUpLoad> archivesManageSingleUpLoads = extra_informationManageVoExtra.getArchivesManageList();
//
//            if (archivesManageSingleUpLoads != null && !archivesManageSingleUpLoads.isEmpty()) {
//                for (ArchivesManageSingleUpLoad archivesManageSingleUpLoad: archivesManageSingleUpLoads) {
//                     String archivesManageSingleUpLoad_archivesId = archivesManageSingleUpLoad.getArchivesId();
//                     if (TextUtils.equals(archivesManageSingleUpLoad_archivesId,archivesId)){
//                         archivesManageVo = archivesManageSingleUpLoad;
//                     }
//                }
//            }

//            if (archivesManageVo != null) {

//        } else {
//            ToastUtils.showShort(getString(R.string.action_abnormal));
//        }

        //编辑按钮 布局
        if (roundTextViewEditAgreeMentRight != null) {
            roundTextViewEditAgreeMentRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Bundle extra_bundle = new Bundle();

                    //最重要的是为了携带【档案的id,外层的】;
                    if (!TextUtils.isEmpty(extra_informationId_id)) {
                        extra_bundle.putString(ExtraKey.EXTRA_VEHICLEID_ID, extra_informationId_id);
                    } else {
                        extra_bundle.putString(ExtraKey.EXTRA_VEHICLEID_ID, archivesManageVo_outSide.getInformationId());
                    }

                    // : 2023-08-29 跳转到-添加单个合同页面，携带这个【合同的id】，目的是为了获取单个合同的详情；
                    if (!TextUtils.isEmpty(extra_archivesId_single)) {
                        extra_bundle.putString(ExtraKey.EXTRA_ARCHIVESMANAGEVO_ID, extra_archivesId_single);
                    } else {
                        if (archivesManageVo_outSide != null) {
                            extra_bundle.putString(ExtraKey.EXTRA_ARCHIVESMANAGEVO_ID, archivesManageVo_outSide.getArchivesId());
                        }
                    }

                    //标志 是 【编辑】过去的
                    extra_bundle.putBoolean(ExtraKey.EXTRA_ARCHIVESMANAGE_VO_IS_EDIT, true);

                    //这里空携带,,编辑信息 ？
                    ActivityUtils.startActivity(extra_bundle, AgreenMentAddSubmitActivity.class);

                }
            });
        }

        if (refreshLayoutInAgreeMentDetail != null) {
            refreshLayoutInAgreeMentDetail.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                    refreshLayout.getLayout().post(new Runnable() {
                        @Override
                        public void run() {

                            gainDatas();

                            refreshLayout.finishRefresh();
                        }
                    });

                }
            });
        }

    }

    private void method_handler_detail(ArchivesManageVo _archivesManageVo) {

        //合同类型 数字格式
        //String type =extra_archivesmanage_vo.getArchiveTypeId();

        //合同类型 汉字形式
        String archivesTypeName = _archivesManageVo.getArchivesTypeName();

        //合同编号
        String archiveNo = _archivesManageVo.getArchiveNo();

        //签约时间
        String signingDate = _archivesManageVo.getSigningDate();

        //购车人
        String partyA = _archivesManageVo.getPartyA();

        //合同金额
        BigDecimal amount = _archivesManageVo.getAmount();

        String amountString = "";
        if (amount != null) {
            amountString = MMKV.defaultMMKV().decodeString(ConstantSign.P_CURRENCYSYMBOL) + amount.toString() + getString(R.string.unitmoney);
        } else {
            amountString = MMKV.defaultMMKV().decodeString(ConstantSign.P_CURRENCYSYMBOL) + CommUtils.formatComma2BigDecimal(0.00).toString() + getString(R.string.unitmoney);
        }

        //filldatas-----------------------------------------------------------------------
        //合同类型
        CommUtils.setText(textView_agreen_type, archivesTypeName);
        //合同编号
        CommUtils.setText(textView_agreen_number, archiveNo);
        //合同签约时间
        CommUtils.setText(textView_agreen_time, signingDate);
        //购车人
        CommUtils.setText(textView_agreen_person, partyA);
        //合同金额
        CommUtils.setText(textView_agreen_price, amountString);

        //合同附件:
        ArrayList<String> list = (ArrayList<String>) _archivesManageVo.getFilePathList();
        npl_item_moment_photos_agreen_detail.setData(list);

        npl_item_moment_photos_agreen_detail.setDelegate(new BGANinePhotoLayout.Delegate() {
            @Override
            public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {

                mCurrentClickNpl = ninePhotoLayout;

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                    photoPreviewWrapper();

                } else {

                    photoPreviewIntentXXPermissions();

                }

            }

            @Override
            public void onClickExpand(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
                ninePhotoLayout.setIsExpand(true);
                ninePhotoLayout.flushItems();
            }
        });

    }

    /**
     * 图片预览，兼容6.0动态权限
     */
    @AfterPermissionGranted(PRC_PHOTO_PREVIEW)
    private void photoPreviewWrapper() {

        if (mCurrentClickNpl == null) {
            return;
        }

        try {
            //do

            String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

            if (EasyPermissions.hasPermissions(this, perms)) {

//                photoPreviewIntent();
                CommTools.photoPreviewIntent(mActivityInstance, AgreenMentDetailActivity.this, mCurrentClickNpl);

            } else {
                //EasyPermissions.requestPermissions(this, "图片预览需要以下权限:\n\n1.访问设备上的照片", PRC_PHOTO_PREVIEW, perms);
                EasyPermissions.requestPermissions(this, StringUtils.getString(R.string.imagenicelook), PRC_PHOTO_PREVIEW, perms);
            }

//            } else {
//                photoPreviewIntentXXPermissions();
//
//            }

        } catch (Exception e) {
            //catch
            e.printStackTrace();
        }

    }

    //图片预览的权限
    private void photoPreviewIntentXXPermissions() {

        if (!XXPermissions.isGranted(AgreenMentDetailActivity.this, com.hjq.permissions.Permission.READ_MEDIA_IMAGES)) {

            CommUtils.checkMaterialDialog(materialDialog);

            materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_ALBUM, new AuthorityCallbackListener() {
                @Override
                public void doSomeThing() {

                    XXPermissions.with(AgreenMentDetailActivity.this)
                            // 适配分区存储应该这样写
                            //.permission(Permission.Group.STORAGE)
                            // 不适配分区存储应该这样写
//                    .permission(com.hjq.permissions.Permission.CAMERA)//
                            .permission(com.hjq.permissions.Permission.READ_MEDIA_IMAGES)//
//                  .permission(com.hjq.permissions.Permission.READ_MEDIA_VIDEO)//
//                  .permission(com.hjq.permissions.Permission.READ_MEDIA_AUDIO)//
                            //).permission(com.hjq.permissions.Permission.MANAGE_EXTERNAL_STORAGE
                            .interceptor(new PermissionInterceptor())
                            .request(new OnPermissionCallback() {

                                @Override
                                public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                    if (!allGranted) {
                                        return;
                                    }

                                    Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                            PermissionNameConvert.getPermissionString(AgreenMentDetailActivity.this, permissions)));

//                                    photoPreviewIntent();
                                    CommTools.photoPreviewIntent(mActivityInstance, AgreenMentDetailActivity.this, mCurrentClickNpl);

                                }
                            });

                    CommUtils.checkMaterialDialog(materialDialog);

                }
            });


        } else {

            CommTools.photoPreviewIntent(mActivityInstance, AgreenMentDetailActivity.this, mCurrentClickNpl);

        }

    }

    //预览相册的能力
//    private void photoPreviewIntent() {
//
////        File downloadDir = new File(Environment.getExternalStorageDirectory(), ConstantSign.BGAPHOTOPICKERDOWNLOAD);
//        File downloadDir = new File(PathUtils.getExternalAppFilesPath(), ConstantSign.BGAPHOTOPICKERDOWNLOAD);
//
//        BGAPhotoPreviewActivity.IntentBuilder photoPreviewIntentBuilder = new BGAPhotoPreviewActivity.IntentBuilder(this);
//
//        if (true) {
//            // 保存图片的目录，如果传 null，则没有保存图片功能
//            photoPreviewIntentBuilder.saveImgDir(downloadDir);
//        }
//
//        if (mCurrentClickNpl.getItemCount() == 1) {
//            // 预览单张图片
//            photoPreviewIntentBuilder.previewPhoto(mCurrentClickNpl.getCurrentClickItem());
//
//        } else if (mCurrentClickNpl.getItemCount() > 1) {
//            // 预览多张图片
//            photoPreviewIntentBuilder.previewPhotos(mCurrentClickNpl.getData())
//                    .currentPosition(mCurrentClickNpl.getCurrentClickItemPosition()); // 当前预览图片的索引
//
//        }
//
//        startActivity(photoPreviewIntentBuilder.build());
//
//    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == PRC_PHOTO_PREVIEW) {
            //Toast.makeText(this, "您拒绝了「图片预览」所需要的相关权限!", Toast.LENGTH_SHORT).show();
            Toast.makeText(this, StringUtils.getString(R.string.image_preview), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void gainDatas() {

        if (NetworkUtils.isConnected()) {

            getServerDatas();

        } else {
            //是否有其他的执行逻辑？
            netWorkError();
//            setEnableLoadmore(refreshLayoutInArchiveDetail, false);

        }

    }

    private void getServerDatas() {

        //String keyWord_upLoad = et_searchInCustomSmall.getText().toString().trim();

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.key, extra_archivesId_single);

        //认证状态：0:待联系;1:待认证;2:已认证;3已取消
//        map.put(Parameterkey.status, "2");
//        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
//        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

//        map.put(Parameterkey.latentType, latentType_upLoad);//,潜客类型 1新车;2二手车
//        map.put(Parameterkey.createsource, createsource_upLoad);//客户来源：0预约试驾；1预约看车；2自然到店；3以旧换新
//        map.put(Parameterkey.status, status_upLoad);////跟进状态：0:待联系;1:已分配;2:有意向;3无意向;4成功;5战败;6取消预约
//        map.put(Parameterkey.keyWord, keyWord_upLoad);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_ARCHIVESMANAGE_GETBYID_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.addInformationManage_getById_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .archivesmanage_getById(extra_archivesId_single)
                .compose(AgreenMentDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<ArchivesManageVo>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        //这里也是遮盖信息
//                        methodNotSuccessData(what_method, serverCode, serverMessage);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            ToastUtils.showShort(serverMessage);
                        }

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        loadingGone();
                    }
                }).subscribe(new Consumer<ArchivesManageVo>() {
                    @Override
                    public void accept(ArchivesManageVo archivesManageVo) throws Throwable {

                        if (archivesManageVo != null) {

                            //重新赋值一次，主要用于【编辑合同】
                            archivesManageVo_outSide = archivesManageVo;

                            //合同详情是：
                            LogUtils.json(ConstantSign.LOGCAT_NOMAL + "携带的合同信息是-", archivesManageVo_outSide);

                            //直接加载详情;
                            method_handler_detail(archivesManageVo);

                            //--------------------------------------------------------------------------------------------------------------------------------
                            //预备合同信息-合同列表信息
//                            ArrayList<ArchivesManageVo> archivesManageList = (ArrayList<ArchivesManageVo>) informationManageVo.getArchivesManageList();
//                            if (archivesManageList != null && !archivesManageList.isEmpty()) {
//                                for (ArchivesManageVo archivesManageVo : archivesManageList) {
//                                    //重新组织合同信息;
//                                    String archivesId = archivesManageVo.getArchivesId();
//                                    if (TextUtils.equals(extra_archivesId, archivesId)) {
//
//                                        //打印这个传递值
//                                        LogUtils.json(ConstantSign.LOGCAT_NOMAL + "-遍历的这条合同是-archivesManageVo-->", archivesManageVo);
//
//                                        archivesManageVo_outSide = archivesManageVo;
//
//                                        break;
//                                    }
//
//                                }

//                                //直接加载详情;
//                                method_handler_detail(archivesManageVo_outSide);
//
//                            }
                        }
                        //-----------------------------------------------------------------------------------------------------
                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        //页面报错；
                    }
                });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadInAgreeMentDetail(EventAgreeMentDetail eventAgreeMentDetail) {

        if (eventAgreeMentDetail != null) {

            if (eventAgreeMentDetail.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_AGREEMENT_DETAIL) {

                getServerDatas();

            }

        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);

    }

    @Override
    protected void methodBack() {
        if (ActivityUtils.isActivityAlive(this)) {
            ActivityUtils.finishActivity(this);
        }
    }

    @Override
    public void processExtraData() {

        //use the data received here
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

//            LogUtils.d(ConstantSign.LOGCAT_NOMAL + extra_jumpfrom_where);

            //携带的是合同的id是，单个的合同id
            extra_archivesId_single = bundle.getString(ExtraKey.EXTRA_ARCHIVESMANAGEVO_ID);

            //携带档案的id.是大范畴的
            extra_informationId_id = bundle.getString(ExtraKey.EXTRA_VEHICLEID_ID);
//          LogUtils.d(ConstantSign.LOGCAT_NOMAL+"合同详情内的-携带档案id是--extra_vehicleid_id--->"+extra_vehicleid_id);

        }

    }
}